package cn.xzqwjw.taskmanager.security;

import cn.xzqwjw.taskmanager.security.filter.AuthJwtFilter;

import cn.xzqwjw.taskmanager.security.handler.AuthJwtFailedHandler;
import cn.xzqwjw.taskmanager.security.handler.JwtRefreshSuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @author rush
 */
public class JwtAuthConfig<T extends JwtAuthConfig<T, B>, B extends HttpSecurityBuilder<B>>
    extends AbstractHttpConfigurer<T, B> {

  private final AuthJwtFilter authJwtFilter;

  public JwtAuthConfig() {
    this.authJwtFilter = new AuthJwtFilter();
  }

  @Override
  public void configure(B http) {
    // 设置 Filter 使用的 AuthenticationManager，这里取公共的即可
    authJwtFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
    // 设置验证成功的 Handler，成功了还要进行刷新jwt的业务操作
    authJwtFilter.setAuthenticationSuccessHandler(new JwtRefreshSuccessHandler());
    // 设置失败的 Handler
    authJwtFilter.setAuthenticationFailureHandler(new AuthJwtFailedHandler());
    // 定义 AuthJwtFilter 过滤器
    AuthJwtFilter filter = postProcess(authJwtFilter);
    // 将 filter 放到 logoutFilter 之前
    http.addFilterBefore(filter, LogoutFilter.class);
  }

  /**
   * 这个配置方法会被Security的Config文件里的链式配置里调用
   */
  public JwtAuthConfig<T, B> permissiveRequestUrls(String... urls) {
    authJwtFilter.setPermissiveUrl(urls);
    return this;
  }

}
